package com.inspur.gs.sbssdl.sbyxgl.djjl.djjl.back.bizactions;

import com.inspur.edp.bef.api.BefRtBeanUtil;
import com.inspur.edp.bef.api.action.VoidActionResult;
import com.inspur.edp.bef.api.be.IBEManagerContext;
import com.inspur.edp.bef.api.be.IBEService;
import com.inspur.edp.bef.api.be.IBusinessEntity;
import com.inspur.edp.bef.api.lcp.ILcpFactory;
import com.inspur.edp.bef.api.lcp.IStandardLcp;
import com.inspur.edp.bef.api.parameter.retrieve.RetrieveParam;
import com.inspur.edp.bef.api.services.IBefSessionManager;
import com.inspur.edp.bef.engine.entity.AssociationInfo;
import com.inspur.edp.bef.spi.action.AbstractManagerAction;
import com.inspur.edp.cdp.coderule.api.CodeRuleBEAssignService;
import com.inspur.edp.cef.entity.changeset.ModifyChangeDetail;
import com.inspur.edp.cef.entity.entity.IEntityData;
import com.inspur.edp.cef.entity.entity.IEntityDataCollection;
import io.iec.edp.caf.commons.utils.SpringBeanUtils;
import lombok.extern.slf4j.Slf4j;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 点检异常单据生成故障单（设备报修）
 */
@Slf4j
public class sbdjjlInspectionErrorPushGzjlMgrAction extends AbstractManagerAction<VoidActionResult> {
    private String dataid;

    public sbdjjlInspectionErrorPushGzjlMgrAction(IBEManagerContext managerContext, String dataid) {
        super(managerContext);
        this.dataid = dataid;
    }

    private static final CodeRuleBEAssignService rule = SpringBeanUtils.getBean(CodeRuleBEAssignService.class);

    @Override
    public void execute() {
        SpringBeanUtils.getBean(IBefSessionManager.class).createSession();
        String inspectconfigID = "ebc8337d-ffb6-4b68-a314-d949ab38a00f";
        String faultConfigID = "36d553b0-e4f7-4aeb-bdf9-c747396ab5a0";
        String beId = "36d553b0-e4f7-4aeb-bdf9-c747396ab5a0";
        String ruleId = "de2bfc50-503b-483c-91ba-ea36f2f49a71";
        try {
            ILcpFactory iLcpFactory = SpringBeanUtils.getBean(ILcpFactory.class);
            IStandardLcp inspectLcp = iLcpFactory.createLcpByBEId(inspectconfigID);
            IEntityData inspectdata = inspectLcp.retrieve(dataid).getData(); //点检单主表数据
            IEntityDataCollection entityDataCollection = inspectdata.getChilds().get("sbdjjlmx");//获取点检明细
            List<IEntityData> errorDetail = entityDataCollection.stream()
                    .filter(detail -> detail.getValue("djresult").equals(4))  //点检结果=4 维修
                    .collect(Collectors.toList());
            ArrayList<IEntityData> errorList = new ArrayList<>();

            for (IEntityData data : entityDataCollection) {
                if (data.getValue("djresult").toString().equals("4")) {
                    errorList.add(data);
                }
            }



            IStandardLcp faultLcp = iLcpFactory.createLcpByBEId(faultConfigID);
            //生成新故障单
            IEntityData data = faultLcp.retrieveDefault();
            String mainId = data.getID().toString();
            ModifyChangeDetail change = new ModifyChangeDetail(mainId);
            String ldbh = getLdbh(beId, ruleId);
            //申请单号
            change.getPropertyChanges().put("Gzdh", ldbh);

            //设备id
            AssociationInfo sbidInfo = new AssociationInfo();
            AssociationInfo inspDevInfo = (AssociationInfo) inspectdata.getValue("sbid");
            sbidInfo.setValue("Sbid", inspDevInfo.getValue("sbid"));
            change.getPropertyChanges().put("Sbid", sbidInfo);

            String sbbz = "";
            if (inspectdata.getValue("sbbz") != null) {
                sbbz = inspectdata.getValue("sbbz").toString();
            }
            String bz = "";
            if (inspectdata.getValue("bz") != null) {
                bz = inspectdata.getValue("bz").toString();
            }

            String djsj = inspectdata.getValue("djsj").toString();
            String gznr = sbbz + djsj + "发现点检异常信息";

            //故障内容
            change.getPropertyChanges().put("Gznr", gznr);

            //故障原因 不填
//            AssociationInfo gzyyInfo = new AssociationInfo();
//            change.getPropertyChanges().put("Gzyy", gzyyInfo);

            //停机台时 暂时设定 0
            BigDecimal tjts = new BigDecimal(BigInteger.ZERO);
            change.getPropertyChanges().put("Tjts", tjts);

            //故障分类 gzfl 不填
//            AssociationInfo gzflInfo = new AssociationInfo();
//            change.getPropertyChanges().put("Gzfl", gzflInfo);

            //故障程度 gzcd 不填
//            AssociationInfo gzcdInfo = new AssociationInfo();
//            change.getPropertyChanges().put("Gzcd", gzcdInfo);

            //故障等级 Gzdj 不填
//            if (map.get("gzdj") != null) {
//                change.getPropertyChanges().put("Gzdj", map.get("gzdj"));
//            }

            //故障部位 拼接点检明细的 点检部位内容
            String djbw = errorDetail.stream()
                    .map(entityData -> entityData.getValue("djbw").toString())
                    .collect(Collectors.joining(","));
            String bw = errorList.stream()
                    .map(entityData -> entityData.getValue("djbw").toString())
                    .collect(Collectors.joining(","));

            change.getPropertyChanges().put("Gzbw", bw);

            //故障时间 -点检时间
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date date = sdf.parse(djsj);
            change.getPropertyChanges().put("Gzsj", date);

            //故障备注
            String wxbz = sbbz + "在" + djsj + "点检发现故障，申请报修";
            change.getPropertyChanges().put("Wxjl", wxbz);

            //维修人员 不填
//            AssociationInfo wxryInfo = new AssociationInfo();
//            change.getPropertyChanges().put("Wxry", wxryInfo);

            //操作人员 不填
//            AssociationInfo czryInfo = new AssociationInfo();
//            change.getPropertyChanges().put("Czry", czryInfo);

            //是否停机
            change.getPropertyChanges().put("IsJhtj", false);
            //计划停机
            change.getPropertyChanges().put("IsJh", false);
            //是否解决
            change.getPropertyChanges().put("IsSolve", false);

            faultLcp.modify(change);
            faultLcp.save();
            //强制从数据库取数，刷新数据
            RetrieveParam retrieveParam = new RetrieveParam();
            retrieveParam.setForceFromRepository(true);
            faultLcp.retrieve(mainId, retrieveParam);

        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        } finally {
            SpringBeanUtils.getBean(IBefSessionManager.class).closeCurrentSession();
        }

    }

    /**
     * @return 生成单据号
     */
    static String getLdbh(String BeId, String RuleId) {
        IStandardLcp enLcp = BefRtBeanUtil.getLcpFactory().createLcpByBEId(BeId);
        IEntityData entityData = enLcp.retrieveDefault();

        enLcp.delete(entityData.getID());

        return rule.generate(BeId, "ldbh", entityData, RuleId);
    }

    private IBusinessEntity getEntity(String dataId) {
        return (IBusinessEntity) super.getBEManagerContext().getEntity(dataId);
    }

    private IBEService getMgr() {
        return (IBEService) super.getBEManagerContext().getBEManager();
    }
}